'''
Created on 2009-12-6

@author: jamiesun
'''
#coding:utf-8
from google.appengine.ext import webapp
from google.appengine.api import urlfetch 
import urllib,logging,sys
from google.appengine.api import users
class ZuosaHandler(webapp.RequestHandler):
    target_url = "http://api.zuosa.com/statuses/update.xml"    
    def get(self):
        title = self.request.get("title")
        url = self.request.get("url")
        self.response.headers['Content-Type'] = 'text/html'
        user = users.get_current_user()
        if not user:
            login = ("<a href=\"%s\">Sign in </a>." %users.create_login_url("/zuosa"))
            self.response.out.write("<html><body>%s</body></html>" % login)
        else:       
            html = """
                <style type="text/css">
                <!--
                textarea {
                    font-size: 12px;
                    border: 1px solid #0066FF;
                    background-color: #FFFFCC;
                }
                .submit {
                    padding: 2px;
                    border: 2px outset #9BB3F9;
                    width: 100px;
                    margin-top: 5px;
                    background-color: #9BB3F9;
                }
                -->
                </style>
                
                <form action="/zuosa" method="post" enctype="application/x-www-form-urlencoded" target="_self">
                  <textarea name="content" cols="50" rows="10">%s %s</textarea>
                  <br />
                  <input name="Submit" type="submit" class="submit" value="submit" />
                </form>        
            """%(title,url)
            self.response.out.write(html)

            
    def post(self):
        user = users.get_current_user()
        if not user:
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write("Illegal Operation")
        else:
            content = self.request.get("content")
            zdata = {"status":content.encode('utf-8')}
            zheaders = {'Authorization':'Basic amFtaWVzdW4ubmV0QGdtYWlsLmNvbTo1OTQxMjM=',
                       'User-Agent':'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
                       'Source':"ShareReader"
                     }
    
            try:
                urlfetch.fetch(url=self.target_url,
                                payload=urllib.urlencode(zdata),
                                method=urlfetch.POST,
                                headers=zheaders)
                self.response.out.write("<script>window.close();</script>")
            except:
                info = sys.exc_info()
                logging.error("zuosa request error %s %s"%(info[0],info[1]))   
                self.response.out.write("<script>window.close();</script>")     

            
